package com.kersci.heartratereader

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.kersci.heartratereader.utils.HeartRateDevice
import com.safframework.log.L

class BleDeviceListAdapter(
    private var deviceList: List<HeartRateDevice>,
    private var itemClickListener: BleDeviceItemClickListener
): RecyclerView.Adapter<BleDeviceListAdapter.ViewHolder>() {

    inner class ViewHolder(view: View, private var itemClickListener: BleDeviceItemClickListener) :
        RecyclerView.ViewHolder(view),
        View.OnClickListener {

        var deviceName: TextView = view.findViewById(R.id.tvDeviceName)
        var deviceMac: TextView = view.findViewById(R.id.tvDeviceMac)
        private var button : Button = view.findViewById(R.id.btnConnectDevice)

        init {
            button.setOnClickListener(this)
        }

        override fun onClick(v: View?) {
            itemClickListener.onItemClick(this.adapterPosition)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.bledevice_item, parent, false)
        return ViewHolder(view, itemClickListener)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        L.d("position - $position:" + deviceList[position].name)
        holder.deviceName.text = deviceList[position].name
        holder.deviceMac.text = deviceList[position].mac

    }

    override fun getItemCount(): Int {
        return deviceList.size
    }

    fun setDeviceList(list: List<HeartRateDevice>) {
        deviceList = list
        L.d("set device list -> " + deviceList.size)
    }
}